﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CFrame.Common;
using CFrame.Request;
using CFrame.Tools;

/*
 * 脚本功能：网络数据处理分发类
 * 编写日期：2018.12.13
 * 编写人：HYZ
 */
namespace CFrame.Manager
{
    public class RequestManager : BaseManager
    {
        //public RequestManager(GameMiddle game) : base(game) { }
        /// <summary>
        /// 缓存所有的请求对应的处理
        /// </summary>
        private Dictionary<int, BaseRequest> requestDict = new Dictionary<int, BaseRequest>();

        public override void OnDestroy()
        {
            
        }

        public override void OnInit()
        {
            
        }

        public override void OnUpdate()
        {
            
        }

        /// <summary>
        /// 注册请求
        /// </summary>
        /// <param name="actionCode">网络请求ID</param>
        /// <param name="request">数据处理脚本</param>
        public void AddRequest(int actionCode,BaseRequest request)
        {
            if(requestDict == null)
            {
                requestDict = new Dictionary<int, BaseRequest>();
            }

            if (requestDict.ContainsKey(actionCode))
            {
                requestDict[actionCode] = request;
            }
            else
            {
                requestDict.Add(actionCode, request);
            }
        }

        /// <summary>
        /// 移除请求
        /// </summary>
        /// <param name="actionCode"></param>
        public void RemoveRequest(int actionCode)
        {
            if (requestDict.ContainsKey(actionCode))
            {
                requestDict.Remove(actionCode);
            }
        }

        /// <summary>
        /// 消息数据分发
        /// </summary>
        /// <param name="actionCode"></param>
        /// <param name="data"></param>
        public void HandleResponse(int actionCode,string data)
        {
            BaseRequest request = requestDict.TryGet<int, BaseRequest>(actionCode);
            if(request == null)
            {
                Debuger.LogWarning("没有注册对应的消息处理模块-->【" + actionCode + "】");
                return;
            }
            //数据下发
            request.OnResponse(data);
        }
    }
}
